package cn.swpu.blog.util;

import cn.swpu.blog.entity.UserInfo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * @Author 冰翔
 * @Date 2021/2/19 14:40
 */
@Component
public class JwtUtil {

    /**
     * key（按照签名算法的字节长度设置key）
     */
    public final static String KEY = "*********";

    /**
     * 过期时间
     */
    public static final Long EXPIRE_TIME = 1000 * 60 * 60 * 2L;


    /**
     * 访问令牌
     * @param userInfo
     * @return
     */
    public String createAccessToken(UserInfo userInfo) {
        return generateJwtToken(userInfo, KEY, EXPIRE_TIME);
    }



    /**
     * 创建 jwt Token
     * @param userInfo 用户基本信息
     * @param KEY 加密的秘钥
     * @param expireTime 过期时间
     * @return 返回的jwt
     */
    public String generateJwtToken(UserInfo userInfo, String KEY, long expireTime) {

        return Jwts.builder()
                .setId(userInfo.getOpenid())
                .setIssuer("jack' blog")
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .claim("authorities", userInfo.getAuthorities().stream()
                        .map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }

    public static void main(String[] args) {
        UserInfo test = new UserInfo("1233", "667", "7788", "test", 0);
        JwtUtil jwtUtil = new JwtUtil();
        System.out.println(jwtUtil.generateJwtToken(test, KEY, 1000000000));
    }


}
